import editForm from "../form.vue";
import batchForm from "../batch-form.vue";
// import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
// import {getMenuList, getPurchaseUserList} from "@/api/system";
import {
  getRechargeApplyList,
  createRechargeApply,
  createBatchRechargeApply,
  updateRechargeApply,
  deleteRechargeApply,
  processRechargeApply
} from "@/api/ads";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { useRoute } from "vue-router";
import type { FormItemProps, RechargeApplyItem, ProcessFormProps, BatchFormItemProps } from "../utils/types";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";

import {
  getStateTagType,
  getStateText,
  formatAmount,
  formatTime,
  canEdit,
  canDelete,
  canProcess,
  processStateOptions,
  formatAccountInfo,
  formatPlatformAgent
} from "../utils/ad-recharge-apply";
import { formRules, processFormRules } from "../utils/rule";

export function useAdRechargeApply() {
  const route = useRoute();
  
  const form = reactive({
    account_id: "",
    state: "",
    platform: "",
    agent_id: "",
    creator_id: "",
    keyword: ""
  });

  const formRef = ref();
  const batchFormRef = ref();
  const processFormRef = ref();
  const dataList = ref<RechargeApplyItem[]>([]);
  const loading = ref(true);
  const stateOptions = ref([]);
  const accountOptions = ref([]);
  const platformOptions = ref([]);
  const agentOptions = ref([]);
  const creatorOptions = ref([]);
  const userOptions = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "申请ID",
      prop: "id",
      width: 80,
      align: "center"
    },
    {
      label: "平台 | 代理商",
      prop: "ad_account",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ ad_account }) => formatPlatformAgent(ad_account)
    },
    {
      label: "广告账号",
      prop: "ad_account",
      minWidth: 120,
      showOverflowTooltip: true,
      formatter: ({ ad_account }) => ad_account?.account_no || "-"
    },
    {
      label: "充值金额",
      prop: "amount",
      width: 120,
      align: "right",
      cellRenderer: ({ row }) => (
        <span style="color: #f56c6c; font-weight: bold;">
          {formatAmount(row.amount || 0)}
        </span>
      )
    },
    {
      label: "申请人",
      prop: "creator",
      width: 100,
      showOverflowTooltip: true,
      formatter: ({ creator }) => creator?.username || "-"
    },
    {
      label: "申请时间",
      prop: "created_at",
      width: 160,
      formatter: ({ created_at }) => formatTime(created_at || 0)
    },
    {
      label: "处理状态",
      prop: "state",
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => (
        <el-tag
          type={getStateTagType(row.state)}
          effect="plain"
          size="small"
        >
          {getStateText(row.state)}
        </el-tag>
      )
    },
    {
      label: "处理时间",
      prop: "feedback_at",
      width: 160,
      formatter: ({ feedback_at }) => formatTime(feedback_at || 0)
    },
    {
      label: "反馈内容",
      prop: "feedback_content",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ feedback_content }) => feedback_content || "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        ...form
      };

      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === "" || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      const { data } = await getRechargeApplyList(params);
      console.log("data", data);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;

      // 更新选项数据
      if (data.state_options) {
        stateOptions.value = data.state_options;
      }
      if (data.account_options) {
        accountOptions.value = data.account_options;
      }
      if (data.platform_options) {
        platformOptions.value = data.platform_options;
      }
      if (data.agent_options) {
        agentOptions.value = data.agent_options;
      }
      if (data.creator_options) {
        creatorOptions.value = data.creator_options;
      }
      if (data.user_options) {
        userOptions.value = data.user_options;
      }
    } catch (error) {
      message("获取数据失败", { type: "error" });
      console.error("获取充值申请列表失败:", error);
    } finally {
      loading.value = false;
    }
  }



  function openDialog(title = "新增", row?: RechargeApplyItem) {
    addDialog({
      title: `${title}充值申请`,
      props: {
        formInline: {
          account_id: row?.account_id || "",
          amount: row?.amount || ""
        }
      },
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, {
        ref: formRef,
        formInline: null,
        accountOptions: accountOptions.value
      }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        FormRef.validate(async (valid) => {
          if (valid) {
            try {
              if (title === "新增") {
                const { data: res } = await createRechargeApply(curData);
                message("创建充值申请成功", { type: "success" });
              } else {
                const { data: res } = await updateRechargeApply({
                  ...curData,
                  id: row!.id
                });
                message("更新充值申请成功", { type: "success" });
              }
              done();
              onSearch();
            } catch (error) {
              message(`${title}失败: ${error.message || "未知错误"}`, { type: "error" });
            }
          }
        });
      }
    });
  }

  function openBatchDialog() {
    addDialog({
      title: "批量新增充值申请",
      props: {
        formInline: {
          accounts: []
        }
      },
      width: "700px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(batchForm, {
        ref: batchFormRef,
        formInline: null,
        accountOptions: accountOptions.value,
        userOptions: userOptions.value
      }),
      beforeSure: (done, { options }) => {
        const FormRef = batchFormRef.value.getRef();
        const curData = options.props.formInline as BatchFormItemProps;

        FormRef.validate(async (valid) => {
          if (valid) {
            try {
              // 转换数据格式
              const submitData = {
                accounts: curData.accounts.map(account => ({
                  account_id: account.account_id,
                  amount: parseFloat(account.amount.toString())
                }))
              };

              const { data: res } = await createBatchRechargeApply(submitData);
              message(`批量创建充值申请成功，共创建 ${curData.accounts.length} 个申请`, { type: "success" });
              done();
              onSearch();
            } catch (error) {
              message(`批量创建失败: ${error.message || "未知错误"}`, { type: "error" });
            }
          }
        });
      }
    });
  }

  function openProcessDialog(row: RechargeApplyItem) {
    const processForm = reactive<ProcessFormProps>({
      state: 2,
      feedback_content: ""
    });

    addDialog({
      title: `处理充值申请`,
      props: {
        formInline: processForm
      },
      width: "500px",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <el-form
          ref={processFormRef}
          model={processForm}
          rules={processFormRules}
          label-width="100px"
        >
                     <el-form-item label="平台代理商">
             <span>{formatPlatformAgent(row.ad_account)}</span>
           </el-form-item>
                     <el-form-item label="广告账号">
             <span>{row.ad_account?.account_no || "-"}</span>
           </el-form-item>
                     <el-form-item label="申请金额">
             <span style="color: #f56c6c; font-weight: bold;">{formatAmount(row.amount || 0)}</span>
           </el-form-item>
          <el-form-item label="处理状态" prop="state">
            <el-radio-group v-model={processForm.state}>
              {processStateOptions.map(option => (
                <el-radio key={option.value} label={option.value}>
                  {option.label}
                  {option.tip && <span style="color: #999; font-size: 12px;">（{option.tip}）</span>}
                </el-radio>
              ))}
            </el-radio-group>
          </el-form-item>
          <el-form-item label="反馈内容" prop="feedback_content">
            <el-input
              v-model={processForm.feedback_content}
              type="textarea"
              rows={3}
              placeholder="请输入处理反馈内容（可选）"
              maxlength={255}
              show-word-limit
            />
          </el-form-item>
        </el-form>
      ),
      beforeSure: async (done) => {
        if (!processFormRef.value) return;

        processFormRef.value.validate(async (valid) => {
          if (valid) {
            try {
              await processRechargeApply(row.id, processForm);
              const statusText = processForm.state === 2 ? "充值" : "驳回";
              message(`申请处理成功，状态已更新为：已${statusText}`, { type: "success" });
              done();
              onSearch();
            } catch (error) {
              message(`处理失败: ${error.message || "未知错误"}`, { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row: RechargeApplyItem) {
    try {
      await deleteRechargeApply({ id: row.id });
      message("删除充值申请成功", { type: "success" });
      onSearch();
    } catch (error) {
      message(`删除失败: ${error.message || "未知错误"}`, { type: "error" });
    }
  }

    onMounted(() => {
    // 检查路由参数，设置默认筛选条件
    const stateParam = route.query.state;
    if (stateParam && stateParam === "1") {
      form.state = 1; // 设置为待处理状态
    }
    
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    stateOptions,
    accountOptions,
    platformOptions,
    agentOptions,
    creatorOptions,
    userOptions,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 分页 */
    handleSizeChange,
    handleCurrentChange,
    /** 新增、修改申请 */
    openDialog,
    /** 批量新增申请 */
    openBatchDialog,
    /** 处理申请 */
    openProcessDialog,
    /** 删除申请 */
    handleDelete,
    /** 选择变化 */
    handleSelectionChange,
    /** 权限判断 */
    canEdit,
    canDelete,
    canProcess
  };
}
